package cn.xudy;

import cn.xudy.group.Application;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;


/**
 * Created by Ulegal on 2017/11/15.
 */

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class test {

    @Autowired
    OSSClient ossClient;

    @Test
    public void OSSUpLoad(){


// 上传
        byte[] content = "Hello OSS".getBytes();
        ossClient.putObject("xudy", "cudy", new ByteArrayInputStream(content));

    }



      @Test
     public void OssAction(HttpServletRequest request, HttpServletResponse response){


          try {
              String fileName="xudy";
              String ossKey="xudy";
              // 从阿里云进行下载
              OSSObject ossObject = ossClient.getObject("xudy",ossKey);//bucketName需要自己设置
              // 已缓冲的方式从字符输入流中读取文本，缓冲各个字符，从而提供字符、数组和行的高效读取
              BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
              //缓冲文件输出流
              BufferedOutputStream outputStream=new BufferedOutputStream(response.getOutputStream());
              //通知浏览器以附件形式下载
              response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
              // 进行解码
              BASE64Decoder base64Decoder = new BASE64Decoder();
              byte[] car;
              while (true) {
                  String line = reader.readLine();
                  if (line == null) break;
                  car =  base64Decoder.decodeBuffer(line);
                  outputStream.write(car);
              }

              reader.close();
              if(outputStream!=null){
                  outputStream.flush();
                  outputStream.close();
              }


          } catch (IOException e) {
              e.printStackTrace();

          } catch (OSSException e){

          }
     }

}
